package com.trkj.exam;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.trkj.base.BaseActivity;
import com.trkj.base.Constants;
import com.trkj.base.OnResponseResultListener;
import com.trkj.base.newwork.ProgressBarDataFromRemote;
import com.trkj.base.utils.UserService;
import com.trkj.taoruiyun.R;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiZanhong on 2015/06/26.
 */
public class ExamDetailActivity extends BaseActivity {
    public static final String ACTION = "com.trkj.exam.ExamDetailActivity";

    @ViewInject(R.id.list)
    private ListView listView;

    private JSONArray array;
    private BitmapUtils bitmapUtils;
    private static final int MAX_TYPE = 3;

    private JSONObject examInfo;//试卷基本信息
    private JSONArray scores; //该试卷的成绩列表

    private void initData(JSONObject data){
        array = new JSONArray();
        JSONArray selector = data.getJSONArray("selector");
        JSONArray judge = data.getJSONArray("jugde");
        JSONArray program = data.getJSONArray("program");

        examInfo = data.getJSONObject("baseInfo");
        scores = data.getJSONArray("chart");

        if(selector != null){
            for(int i = 0; i < selector.size(); i ++){
                JSONObject obj = new JSONObject();
                obj.put("question_title", selector.getJSONObject(i).getString("question_title"));
                obj.put("a", selector.getJSONObject(i).getString("a"));
                obj.put("b", selector.getJSONObject(i).getString("b"));
                obj.put("c", selector.getJSONObject(i).getString("c"));
                obj.put("d", selector.getJSONObject(i).getString("d"));
                obj.put("answer", selector.getJSONObject(i).getString("answer"));
                obj.put("correct_answer", selector.getJSONObject(i).getString("correct_answer"));
                obj.put("image_file", selector.getJSONObject(i).getString("image_file"));
                obj.put("type", Constants.QuestionType.SELECT);
                array.add(obj);
            }
        }

        if(judge != null){
            for(int i = 0; i < judge.size(); i ++){
                JSONObject obj = new JSONObject();
                obj.put("question_title", judge.getJSONObject(i).getString("question_title"));
                obj.put("answer", judge.getJSONObject(i).getString("answer"));
                obj.put("correct_answer", judge.getJSONObject(i).getString("correct_answer"));
                obj.put("image_file", judge.getJSONObject(i).getString("image_file"));
                obj.put("type", Constants.QuestionType.JUDGE);
                array.add(obj);
            }
        }

        if(program != null){
            for(int i = 0; i < program.size(); i ++){
                JSONObject obj = new JSONObject();
                obj.put("question_title", program.getJSONObject(i).getString("question_title"));
                obj.put("answer", program.getJSONObject(i).getString("answer"));
                obj.put("correct_answer", program.getJSONObject(i).getString("correct_answer"));
                obj.put("image_file", program.getJSONObject(i).getString("image_file"));
                obj.put("type", Constants.QuestionType.PROGRAM);
                array.add(obj);
            }
        }

        Log.d("array.length", String.valueOf(array.size()));
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem miExamInfo = menu.add(Menu.NONE, Constants.MenuID.MENU_EXAM_INFO, Menu.NONE, "试卷信息");
        MenuItem miScores = menu.add(Menu.NONE, Constants.MenuID.MENU_EXAM_SCORE, Menu.NONE, "分数排名");

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case Constants.MenuID.MENU_EXAM_INFO:
                createExamInfoDialog();
                break;
            case Constants.MenuID.MENU_EXAM_SCORE:
                createExamScoresDialog();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 查看试卷基本信息
     */
    private void createExamInfoDialog(){
        class Pairs{
            String key;
            String value;
            int type; //显示几列,1为1列，2为2列

            public Pairs(String key, String value) {
                this.key = key;
                this.value = value;
                type = 2;
            }

            public Pairs(String key, String value, int type) {
                this.key = key;
                this.value = value;
                this.type = type;
            }
        }


        class ExamInfoAdapter extends BaseAdapter{
            private List<Pairs> list;

            public ExamInfoAdapter(){
                if(examInfo != null){
                    list = new ArrayList<Pairs>();
                    list.add(new Pairs(examInfo.getString("exam_name"), "", 1));
                    list.add(new Pairs("得分", examInfo.getString("what_score")));
                    list.add(new Pairs("课程", examInfo.getString("level_name")));
                    list.add(new Pairs("章节", examInfo.getString("chapter_name")));
                    list.add(new Pairs("考生", examInfo.getString("exam_user_name")));
                    list.add(new Pairs("选择题数", examInfo.getString("selector_count")));
                    list.add(new Pairs("判断题数", examInfo.getString("jugde_count")));
                    list.add(new Pairs("编程题数", examInfo.getString("program_count")));
                    list.add(new Pairs("参考时间", examInfo.getString("exam_time") + "分钟"));
                    list.add(new Pairs("试题类型",
                            examInfo.getIntValue("exam_type") == 1 ? "考试" : "练习"));
                    list.add(new Pairs("出题人", examInfo.getString("user_name")));
                }
            }

            @Override
            public int getCount() {
                return list == null ? 0 : list.size();
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public int getItemViewType(int position) {
                if(list == null) return 0;

                if(list.get(position).type == 1){
                    return 0;
                }else{
                    return 1;
                }
            }

            @Override
            public int getViewTypeCount() {
                return 2;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                final MenuViewHolder viewHolder;
                if(getItemViewType(position) == 0){
                    //显示为1列
                    if(convertView == null){
                        convertView = LayoutInflater.from(ExamDetailActivity.this)
                                .inflate(android.R.layout.simple_list_item_1, null);
                        viewHolder = new MenuViewHolder();
                        viewHolder.key = (TextView)convertView.findViewById(android.R.id.text1);
                        convertView.setTag(viewHolder);
                    }else{
                        viewHolder = (MenuViewHolder)convertView.getTag();
                    }

                    viewHolder.key.setText(list.get(position).key);
                }else{
                    //显示为2列
                    if(convertView == null){
                        convertView = LayoutInflater.from(ExamDetailActivity.this)
                                .inflate(R.layout.two_item, null);
                        viewHolder = new MenuViewHolder();
                        viewHolder.key = (TextView)convertView.findViewById(R.id.key);
                        viewHolder.value = (TextView)convertView.findViewById(R.id.value);
                        convertView.setTag(viewHolder);
                    }else{
                        viewHolder = (MenuViewHolder)convertView.getTag();
                    }

                    viewHolder.value.setText(list.get(position).value);
                    viewHolder.key.setText(list.get(position).key);
                }

                return convertView;
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setAdapter(new ExamInfoAdapter(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    /**
     * 查看分数排行榜
     */
    private void createExamScoresDialog(){
        class ScoreAdapter extends BaseAdapter{
            @Override
            public int getCount() {
                return scores == null ? 0 : scores.size();
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if(scores == null) return convertView;

                final MenuViewHolder viewHolder;
                if(convertView == null){
                    convertView = LayoutInflater.from(ExamDetailActivity.this)
                        .inflate(R.layout.two_item, null);
                    viewHolder = new MenuViewHolder();
                    viewHolder.key = (TextView)convertView.findViewById(R.id.key);
                    viewHolder.value = (TextView)convertView.findViewById(R.id.value);
                    convertView.setTag(viewHolder);
                }else{
                    viewHolder = (MenuViewHolder)convertView.getTag();
                }

                String s = scores.getJSONObject(position).getString("what_score");
                if(TextUtils.isEmpty(s)){
                    viewHolder.value.setText("未提交");
                }else{
                    viewHolder.value.setText(s);
                }
                viewHolder.key.setText(scores.getJSONObject(position).getString("user_name"));


                return convertView;
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("分数排行榜")
                .setAdapter(new ScoreAdapter(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exam_detail);
        ViewUtils.inject(this);
        bitmapUtils = new BitmapUtils(ExamDetailActivity.this);

        ProgressBarDataFromRemote dataFromRemote
                = new ProgressBarDataFromRemote(this);
        dataFromRemote.setResponseResultListener(new OnResponseResultListener() {
            @Override
            public void onResponseResult(String result) {
                JSONObject jsonObject = JSON.parseObject(result);
                if(jsonObject.getBoolean("success")){
                    initData(jsonObject.getJSONObject("data"));
                    listView.setAdapter(new ExamDetailAdapter());
                }else{
                    toast("试卷拉取失败");
                }
            }
        });

        //获得试卷id
        Intent intent = getIntent();
        int examId = intent.getIntExtra("examId", 0);
        Log.d("examId", String.valueOf(examId));
        String url = MessageFormat.format(Constants.ApiUrl.EXAM_DETAIL,
                UserService.getInstance(this).parseUser().userId,
                examId);
        dataFromRemote.execute(url);
    }

    @Override
    protected String getCustomerTitle() {
        return "试卷详情";
    }

    class ExamDetailAdapter extends BaseAdapter{
        @Override
        public int getCount() {
            return array == null ? 0 : array.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(array == null) return convertView;

            JSONObject object = array.getJSONObject(position);
            int type = object.getIntValue("type");

            if(type == Constants.QuestionType.SELECT){
                final SelectorViewHolder viewHolder;
                if(convertView == null){
                    convertView = LayoutInflater.from(ExamDetailActivity.this)
                            .inflate(R.layout.activity_exam_select_item, null);
                    viewHolder = new SelectorViewHolder();
                    viewHolder.questionTitle = (TextView) convertView.findViewById(R.id.question_title);
                    viewHolder.a = (TextView) convertView.findViewById(R.id.a);
                    viewHolder.b = (TextView) convertView.findViewById(R.id.b);
                    viewHolder.c = (TextView) convertView.findViewById(R.id.c);
                    viewHolder.d = (TextView) convertView.findViewById(R.id.d);
                    viewHolder.answer = (TextView) convertView.findViewById(R.id.answer);
                    viewHolder.connectAnswer = (TextView) convertView.findViewById(R.id.correct_answer);
                    viewHolder.imageFile = (ImageView) convertView.findViewById(R.id.image_file);

                    convertView.setTag(viewHolder);
                }else{
                    viewHolder = (SelectorViewHolder)convertView.getTag();
                }

                viewHolder.questionTitle.setText((position + 1) + "、" +
                        Html.fromHtml(object.getString("question_title")));
                viewHolder.a.setText("A、" + Html.fromHtml(object.getString("a")));
                viewHolder.b.setText("B、" + Html.fromHtml(object.getString("b")));
                viewHolder.c.setText("C、" + Html.fromHtml(object.getString("c")));
                viewHolder.d.setText("D、" + Html.fromHtml(object.getString("d")));
                viewHolder.answer.setText("你的答案：" + object.getString("answer"));
                viewHolder.connectAnswer.setText("参考答案：" + object.getString("correct_answer"));

                if(object.getString("answer").equals(object.getString("correct_answer"))){
                    viewHolder.answer.setTextColor(Constants.Color.getColor(ExamDetailActivity.this,
                            R.color.black));
                }else{
                    viewHolder.answer.setTextColor(Constants.Color.getColor(ExamDetailActivity.this,
                            R.color.red));
                }

                String img = object.getString("image_file");
                if(img != null){
                    viewHolder.imageFile.setVisibility(View.VISIBLE);
                    bitmapUtils.display(viewHolder.imageFile, Constants.ApiUrl.HTTP_GSON_CN + "/upload/" + img);
                }else{
                    viewHolder.imageFile.setVisibility(View.GONE);
                }

            }else if(type == Constants.QuestionType.JUDGE
                    || type == Constants.QuestionType.PROGRAM){
                final ViewHolder viewHolder;
                if(convertView == null){
                    if(type == Constants.QuestionType.JUDGE) {
                        convertView = LayoutInflater.from(ExamDetailActivity.this)
                                .inflate(R.layout.activity_exam_judge_item, null);
                    }else if(type == Constants.QuestionType.PROGRAM){
                        convertView = LayoutInflater.from(ExamDetailActivity.this)
                                .inflate(R.layout.activity_exam_program_item, null);
                    }

                    viewHolder = new ViewHolder();
                    viewHolder.questionTitle = (TextView) convertView.findViewById(R.id.question_title);
                    viewHolder.answer = (TextView) convertView.findViewById(R.id.answer);
                    viewHolder.answer = (TextView) convertView.findViewById(R.id.answer);
                    viewHolder.connectAnswer = (TextView) convertView.findViewById(R.id.correct_answer);
                    viewHolder.imageFile = (ImageView) convertView.findViewById(R.id.image_file);

                    convertView.setTag(viewHolder);
                }else{
                    viewHolder = (ViewHolder)convertView.getTag();
                }

                viewHolder.questionTitle.setText((position + 1) + "、"
                        + Html.fromHtml(object.getString("question_title")));
                viewHolder.answer.setText(Html.fromHtml(
                        (type == Constants.QuestionType.JUDGE ? "你的答案：" : "你的答案：<br>")
                        + object.getString("answer")));
                String correctAnswer = object.getString("correct_answer");
                if(viewHolder.connectAnswer != null) {
                    viewHolder.connectAnswer.setText("参考答案：" + correctAnswer);
                }

                if(type == Constants.QuestionType.JUDGE) {
                    if (object.getString("answer").equals(object.getString("correct_answer"))) {
                        viewHolder.answer.setTextColor(Constants.Color.getColor(ExamDetailActivity.this,
                                R.color.black));
                    } else {
                        viewHolder.answer.setTextColor(Constants.Color.getColor(ExamDetailActivity.this,
                                R.color.red));
                    }
                }

                String img = object.getString("image_file");
                if(img != null){
                    viewHolder.imageFile.setVisibility(View.VISIBLE);
                    bitmapUtils.display(viewHolder.imageFile, Constants.ApiUrl.HTTP_GSON_CN + "/upload/" + img);
                }else{
                    viewHolder.imageFile.setVisibility(View.GONE);
                }
            }

            return convertView;
        }

        @Override
        public int getItemViewType(int position) {
            JSONObject obj = array.getJSONObject(position);
            return obj.getIntValue("type");
        }

        @Override
        public int getViewTypeCount() {
            return MAX_TYPE;
        }

        class SelectorViewHolder{
            TextView questionTitle;
            TextView a;
            TextView b;
            TextView c;
            TextView d;
            TextView answer;
            TextView connectAnswer;
            ImageView imageFile;
        }

        class ViewHolder{
            TextView questionTitle;
            TextView answer;
            TextView connectAnswer;
            ImageView imageFile;
        }
    }

    class MenuViewHolder{
        TextView key;
        TextView value;
    }
}
